#include <robot_schedule/Monitor.h>

#define FREEDOM_STATE_SECOND 10

Monitor::Monitor() : started(false), running(false), t(NULL) {}

Monitor::~Monitor() {
	if(t){
		delete t;
		t = NULL;
	}
}

void Monitor::run(){
	if(!running){ // 判断线程是否已启动
		running = true;
		t = new thread(&Monitor::loop, this);
	}
}

void Monitor::loop()
{
	while (running)
	{
		if (!started)
		{ // 如果监控没有被start(), 则等待
			std::unique_lock<std::mutex> loc(mutStart);
			condStart.wait(loc);
		}

		this_thread::sleep_for(chrono::seconds(1)); // 休眠1s

		endTime = system_clock::now();
		// Sleep(1);
		duration<double> duration = endTime - startTime;

		cout << duration.count() << "s" << endl;

		if (duration.count() < FREEDOM_STATE_SECOND)
		{
			continue;
		}

		// .. 进入自由模式
		enterFreedomMode();
		started = false;
	}
}

// 开始监控
void Monitor::start()
{
	endTime = startTime = system_clock::now();
	started = true;

	condStart.notify_one();
	cout << "condStart.notify_one()." << endl;
}

// 停止监控
void Monitor::stop()
{
	started = false;
	running = true;
	
	this_thread::sleep_for(chrono::milliseconds(1000));

	if(t){
		delete t;
		t = NULL;
	}
}

// 进入自由模式
void Monitor::enterFreedomMode()
{
	cout << "enterFreedomMode()." << endl;
}

// 进入正常模式
void Monitor::enterNormalMode()
{
	cout << "enterNormalMode()." << endl;
}
